#include <mfile.h>
#include <easy_sock.h>
#include <demo.h>
#include <mlog.h>
#include <appdef.h>

#define PORT 1234
#define IPADDR "127.0.0.1"

int recv_file( int ,FINFO );

int main(int argc, char *args[])
{
    RQ rq;
    RS rs;
    int sfd;
    char sbuf[BUF_LEN];
    int num,fnum;
    char rbuf[BUF_LEN];
    FINFO fi;
    
    memset( &rq, 0x00, sizeof(RQ) );
    memset( sbuf, 0x00, sizeof(sbuf) );

    if( argc != 2 )
    {
        printf("usage:\n%s filename\n", args[0]);
        return 0;
    }


    sfd=connect_to( IPADDR, PORT );
    if( sfd == -1)
    {
        mlog("fcli.log", _FL_, "connect failed!" );
        printf("connection failed\n");
        return 1;
    }
    /*construct a request*/
    strcpy( rq.rq_name, "GETFILE" );
    strcpy( rq.rq_str, args[1] );
    /*format struct into a string buffer for socket send*/
    memcpy( sbuf, &rq, sizeof(RQ) );

     /*send request*/
    PCHECK(num=send( sfd, sbuf, sizeof(sbuf), 0 ), "send" );
    
    /*get response*/
    PCHECK(num=recv(sfd, rbuf, sizeof(rbuf), 0 ), "recv" );
    /*analysis response*/
    /*for test*/
    /*printf( "get response %d byte(s)\n", num);*/
    memset( &rs, 0x00, sizeof(RS) );
    memcpy( &rs, rbuf, sizeof(RS) );
    if( rs.code == M_FAIL )
    {
        printf("request refused!\nmsg[%s]\n", rs.msg);
        return 1;
    }
    else
    {
        printf("request is accept\n" );
        memset( &fi, 0x00, sizeof(FINFO) );
        memcpy( &fi, rs.msg, sizeof(FINFO) );
        printf("get file info: filename[%s] file_len[%lu]\n", fi.f_name, fi.f_size);
    }
    
    fnum = recv_file( sfd, fi );
    close( sfd );
    return 0;
   
}

/*get file content from socket and save file*/
int recv_file(int sock_fd,FINFO fi)
{
    char buf[2048];
    int f_len;
    FILE *fp;
    int rnum,wnum;
    
    /*open a file to wirte*/
    if ( (fp=fopen( fi.f_name, "wb")) == NULL )
    {
        printf( "open file failed!" );
        return -1;
    }
    
    /*begin to recv file*/
    f_len = 0;
    printf( "ready to transform...\n");
    while( f_len != fi.f_size )
    {
        memset( buf, 0x00, sizeof(buf) );
        PCHECK( (rnum = recv( sock_fd, buf, sizeof(buf), 0 )) ,"recv" );
        /*rnum=read( sock_fd, buf, sizeof(buf) );*/
        
        if( rnum > 0 )
        {
            wnum = fwrite( buf, 1, rnum, fp );
            f_len += wnum;
        }
    }
    
    close(fp);
    printf( "get file %s succ totol %d byte(s)\n", fi.f_name, f_len);
    return f_len;
}